import Utils from "../../../Utils";
import { AiEnvironment } from "./AiGameAction";


export abstract class DecisionNode {
    childDecisionNodes: DecisionNode[];
    environment: AiEnvironment
    constructor(environment: any) {
        this.childDecisionNodes = [];
        this.environment = environment
    }

    /**
     * 评估此决定后返回得分
     * @param context 
     */
    abstract evaluate(): number

    /**
     * 执行此决定
     * 在子决策中按得分(概率)随机选择
     * @param context 
     */
    execute(): number {
        let scores: number[] = this.childDecisionNodes.map(node => node.evaluate());
        let fianlNodes: DecisionNode[] = [];
        let finalScore: number[] = [];

        scores.forEach((score: number, index: number) => {
            if (score > 0) {
                fianlNodes.push(this.childDecisionNodes[index]);
                finalScore.push(score);
            }
        });
        if (fianlNodes.length) {
            let randomIndex = Utils.getRandomIndexByProbability(finalScore);
            return fianlNodes[randomIndex].execute();
        } else {
            return Utils.getRandom(10, 15);
        }
    }
}

export class DecisionTree {
    private root: DecisionNode;

    constructor(root: DecisionNode) {
        this.root = root;
    }

    decide(): number {
        return this.root.execute();
    }
}

